package cn.oop.date;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class VisualCalendar {
    public static void main(String[] args) {
        String temp = "2030-02-10";
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = format.parse(temp);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            int day = calendar.get(Calendar.DATE);
            System.out.println("day :" + day);

            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            calendar.set(Calendar.YEAR, 2000);
            calendar.set(Calendar.DATE, 8);

            int day2 = calendar.get(Calendar.DATE);
            System.out.println("day2 :" + day2);

            System.out.println("day of week : " + dayOfWeek);

            System.out.println();
            Date nowDate = calendar.getTime();
            System.out.println(format.format(nowDate));

            int weekOfFirstDay = getFirstDayWeek(nowDate);

            int monthDay = getMonthDayCount(nowDate);

            System.out.println("month day count  " + monthDay);

            printCalendar(weekOfFirstDay, monthDay);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private static void printCalendar(int weekOfFirstDay, int monthDay) {

        System.out.println("日\t一\t二\t三\t四\t五\t六");

        for (int i = 0; i < weekOfFirstDay; i++) {
            System.out.print("\t");
        }

        for (int i = 1; i <= monthDay; i++) {
            System.out.print(i);
            if ((i + weekOfFirstDay) % 7 == 0) {
                System.out.print("\n");
            } else {
                System.out.print("\t");
            }
        }
    }

    private static int getFirstDayWeek(Date nowDate) {

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date firtDay = calendar.getTime();
        System.out.println("firstDay " + format.format(firtDay));

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println("Day of week " + dayOfWeek);

        return dayOfWeek;
    }

    private static int getMonthDayCount(Date nowDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);

        calendar.set(Calendar.DATE, 1);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DATE, -1);

        return calendar.get(Calendar.DATE);
    }
}
